package com.mine.async.aspect;

import cn.hutool.core.util.BooleanUtil;
import com.mine.async.annotation.DownloadRetry;
import com.mine.async.jobexe.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DownloadRetryAspect {


    @Pointcut("@annotation(com.mine.async.annotation.DownloadRetry)")
    private void cutMethod() {

    }

    /**
     * 环绕通知：灵活自由的在目标方法中切入代码
     */
    @Around("cutMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Object[] params = joinPoint.getArgs();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            DownloadRetry downloadRetry = method.getAnnotation(DownloadRetry.class);
            PageQuery pageQuery = getPageQuery(params);
            if (pageQuery != null && !BooleanUtil.isTrue(pageQuery.getIsRetryOperate())) {
                setPageQuery(downloadRetry, pageQuery, method.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return joinPoint.proceed();
    }

    private PageQuery getPageQuery(Object[] params) {
        for (Object object : params) {
            if (object instanceof PageQuery) {
                return (PageQuery) object;
            }
        }
        return null;
    }

    private void setPageQuery(DownloadRetry downloadRetry, PageQuery pageQuery, String methodName) {
        String beanClassName = downloadRetry.beanClass().getName();
        String paramClassName = downloadRetry.paramClass().getName();
        int retryCount = downloadRetry.retryCount();
        boolean retryFlag = downloadRetry.retryFlag();
        if (pageQuery != null) {
            pageQuery.setBeanClassName(beanClassName);
            pageQuery.setParamClassName(paramClassName);
            pageQuery.setMethodName(methodName);
            pageQuery.setRetryCount(retryCount);
            pageQuery.setRetryFlag(retryFlag);
            pageQuery.setIsRetryOperate(false);

        }
    }

}
